<?php
/**
 * DeSensitive Security Data String
 *
 * Author: JennyWang
 * Date: 2018/4/11
 * Time: 21:36
 * Created by PhpStorm.
 */
namespace App\Models\Concerns;


use Illuminate\Database\Eloquent\Model;

/**
 * @mixin Model
 * @property string $asterisk_email
 * @property string $asterisk_phone
 */
trait DeSensitive
{
    /**
     * @used-by $asterisk_email - 返回插入 * 号的去敏感邮箱字符串
     *
     * @test
     * @example
     *   ab@email.com => ab@email.com
     *   abc@email.com => ab*@email.com
     *   abcdefg@email.com => ab***fg@email.com
     *   abcdefghklmnopqrst@email.com => ab***********fg@email.com
     *
     * @return string
     */
    public function getAsteriskEmailAttribute(): string
    {
        $start_char = '(\w{2})';$mid_char = '(.*?)';$end_char='(\w{0,2})';$email_suffix = '(@.*)';

        return preg_replace_callback(
            "/{$start_char}{$mid_char}{$end_char}{$email_suffix}/",
            function (array $matches) {
                $mid_idx = 2;$end_idx = 3;

                if (strlen($matches[$mid_idx])) {
                    $matches[$mid_idx] = str_repeat('*', strlen($matches[$mid_idx]));
                } else {
                    $matches[$end_idx] = str_repeat('*', strlen($matches[$end_idx]));
                }

                unset($matches[0]);
                return implode('', $matches);
            },
            $this->email
        );
    }

    /**
     * @used-by $asterisk_phone - 返回插入 * 号的去敏感手机字符串
     * @test
     *
     * @example
     *   15612349229 => 156****9229
     *   15612349 => 156*9229
     *   156123 => 156123
     *   0086-15612349229 => 008*********9229
     *
     * @return string
     */
    public function getAsteriskPhoneAttribute(): string
    {
        $start_char = '(\d{3})';$mid_char = '(.*?)';$end_char='(\d{4})$';;

        return preg_replace_callback(
            "/{$start_char}{$mid_char}{$end_char}/",
            function (array $matches) {
                $mid_idx = 2;

                $matches[$mid_idx] = str_repeat('*', strlen($matches[$mid_idx]));

                unset($matches[0]);
                return implode('', $matches);
            },
            $this->phone
        );
    }
}